package dao;

import model.User;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class UserDao {
    // 用户登录方法
    public boolean Login(User user) throws SQLException {
        MyDB myDB = new MyDB();
        try (ResultSet resultSet = myDB.query("select * from user where name ='" + user.getName() + "' and password = '" + user.getPassword() + "'")) {
            try {
                if (resultSet.next()) {
                    return true;
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return false;
    }

    // 获取所有的用户
    public ArrayList<User> getAllUser() {
        MyDB myDB = new MyDB();
        ArrayList<User> res = new ArrayList<>();
        try {
            try (ResultSet resultSet = myDB.query("select * from user")) {
                while (resultSet.next()) {
                    User user = new User();
                    user.setId(resultSet.getInt("id"));
                    user.setName(resultSet.getString("name"));
                    user.setPassword(resultSet.getString("password"));
                    user.setEmail(resultSet.getString("email"));
                    user.setInfo(resultSet.getString("info"));
                    res.add(user);
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        return res;
    }

    // 获取用户总数
    public int getCount() {
        MyDB myDB = new MyDB();
        try {
            try (ResultSet resultSet = myDB.query("select count(*) as t from user")) {
                resultSet.next();
                return resultSet.getInt("t");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    // 创建用户方法
    public boolean regUser(User user) {
        MyDB myDB = new MyDB();
        // 至少得用户名和密码不为空
        if (user.getName() == null || user.getPassword() == null) {
            return false;
        } else {
            try {
                PreparedStatement preparedStatement = myDB.getPreparedStatement("insert into user (name,password,sex,Email,info) values(?,?,?,?,?)");
                preparedStatement.setString(1, user.getName());
                preparedStatement.setString(2, user.getPassword());
                preparedStatement.setString(3, user.getSex());
                preparedStatement.setString(4, user.getEmail());
                preparedStatement.setString(5, user.getInfo());
                preparedStatement.executeUpdate();
                return true;
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

